import React from 'react'
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend
} from 'chart.js'
import { Doughnut } from 'react-chartjs-2'

ChartJS.register(ArcElement, Tooltip, Legend)

interface DoughnutChartProps {
  value: number
  maxValue?: number
  label: string
  color: string
  backgroundColor?: string
  size?: number
  showPercentage?: boolean
  unit?: string
}

const DoughnutChart: React.FC<DoughnutChartProps> = ({
  value,
  maxValue = 100,
  label,
  color,
  backgroundColor = '#f3f4f6',
  size = 120,
  showPercentage = true,
  unit = '%'
}) => {
  const percentage = Math.min((value / maxValue) * 100, 100)
  const remaining = 100 - percentage

  const data = {
    datasets: [
      {
        data: [percentage, remaining],
        backgroundColor: [color, backgroundColor],
        borderWidth: 0,
        cutout: '70%'
      }
    ]
  }

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false
      },
      tooltip: {
        enabled: false
      }
    },
    animation: {
      animateRotate: true,
      duration: 1000
    }
  }

  // 根据百分比确定颜色
  const getColor = (percent: number) => {
    if (percent >= 90) return '#ef4444' // 红色 - 危险
    if (percent >= 75) return '#f59e0b' // 橙色 - 警告
    if (percent >= 50) return '#3b82f6' // 蓝色 - 正常
    return '#10b981' // 绿色 - 良好
  }

  const displayColor = color === 'auto' ? getColor(percentage) : color

  const updatedData = {
    ...data,
    datasets: [
      {
        ...data.datasets[0],
        backgroundColor: [displayColor, backgroundColor]
      }
    ]
  }

  return (
    <div className="relative inline-block" style={{ width: size, height: size }}>
      <Doughnut data={updatedData} options={options} />
      
      {/* 中心文本 */}
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <div className="text-2xl font-bold" style={{ color: displayColor }}>
          {showPercentage ? `${percentage.toFixed(1)}${unit}` : value.toLocaleString()}
        </div>
        <div className="text-xs text-gray-500 text-center mt-1 max-w-16 leading-tight">
          {label}
        </div>
      </div>
    </div>
  )
}

export default DoughnutChart
